package Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyp
 * date 2022-03-08
 */
public class VerifyLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        if (uri.equals("/") || uri.equals("/index.html") || uri.equals("/login.do") || uri.equals("/register.do")) {
            filterChain.doFilter(request, response);
        } else {
            if (request.getSession().getAttribute("loginUser") == null) {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().println("<script> alert('对不起，您这个B没登陆就想访问？？登陆了再来！');window.location.href='/index.html' </script>");
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
